package cn.itcast.users.service.impl;

import cn.itcast.constant.JwtClaimsConstant;
import cn.itcast.constant.MessageConstant;
import cn.itcast.exception.LoginFailedException;
import cn.itcast.properties.JwtProperties;
import cn.itcast.properties.WeChatProperties;
import cn.itcast.users.dto.UserLoginDTO;
import cn.itcast.users.mapper.UserMapper;
import cn.itcast.users.pojo.User;
import cn.itcast.users.service.UserService;
import cn.itcast.users.vo.UserLoginVO;
import cn.itcast.users.vo.UserReportVO;
import cn.itcast.utils.HttpClientUtil;
import cn.itcast.utils.JwtUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private WeChatProperties weChatProperties;


    @Autowired
    private UserMapper userMapper;

    /**
     * 用户端微信登录
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public UserLoginVO wxLogin(UserLoginDTO userLoginDTO) {

        // openid,通过微信官方接口获取
        Map<String, String> param = new HashMap<>();
        param.put("appid", weChatProperties.getAppid());
        param.put("secret", weChatProperties.getSecret());
        param.put("js_code", userLoginDTO.getCode());
        param.put("grant_type", "authorization_code");

        // 发送请求
        String body = HttpClientUtil.doGet(WX_LOGIN, param);
        String openid = (String) JSONObject.parseObject(body).get("openid");

        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        // 判断用户是否为第一次登录，第一次登录需要在数据库中添加
        User user = userMapper.getByOpenid(openid);
        if (user == null) {
            // 若表中没有用户信息则说明是第一次登录，需用进行注册添加
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            // 新增用户，主键自增并返回
            userMapper.insert(user);
        }

        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());

        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);


        return UserLoginVO.builder()
                .openid(openid)
                .id(user.getId())
                .token(token)
                .build();
    }

    /**
     * 用户统计接口
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<String> dateList = new ArrayList<>(); // 日期列表
        List<Integer> newUserList = new ArrayList<>(); // 新增用户数列表
        List<Integer> totalUserList = new ArrayList<>(); // 总用户量列表


        while (!begin.isAfter(end)) {

            Map<String, Object> map = new HashMap<>();
            map.put("start", LocalDateTime.of(begin, LocalTime.MIN));
            map.put("end", LocalDateTime.of(begin, LocalTime.MAX));
            Integer newUserCount = userMapper.getUserReportByMap(map);

            map.put("start", null);
            Integer totalUserCount = userMapper.getUserReportByMap(map);

            dateList.add(begin.toString());
            newUserList.add(newUserCount);
            totalUserList.add(totalUserCount);

            begin = begin.plusDays(1);
        }


        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    /**
     * 根据id查询用户信息
     *
     * @param id
     * @return
     */
    @Override
    public User getById(Long id) {
        return userMapper.getById(id);
    }
}
